<template>
  <div class="addRole-dialog">
    <base-dialog
      :model="addData.isOpen"
      @close="closeDialogHandle"
      :title="addData.title"
    >
      <template #body>
        <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model.trim="formData.roleName"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model.trim="formData.remarks"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="addData.isOpen = false">取 消</el-button>
        <el-button type="primary" @click="addRoleHandle">确 定</el-button>
      </template>
    </base-dialog>
  </div>
</template>

<script>
import { addRole, getRoleInfoById } from '@/api/system'
export default {
  props: {
    addData: {
      type: Object
    }
  },
  data () {
    return {
      formData: {
        roleName: '',
        remarks: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          {
            min: 2,
            max: 15,
            message: '长度在 2 到 15 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    'addData.isOpen': function (isOpen) {
      if (this.addData.type === 'edit') {
        this.getRoleInfoById()
      }
      if (!isOpen) {
        this.formData = {
          roleName: '',
          remarks: ''
        }
      }
    }
  },
  methods: {
    // 根据id获取角色信息
    getRoleInfoById () {
      getRoleInfoById(this.addData.id).then(res => {
        Object.keys(this.formData).forEach((item) => {
          this.formData[item] = res.data[item]
        })
        this.formData.id = this.addData.id
      })
    },
    // 添加角色
    addRoleHandle () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          addRole(this.formData).then(res => {
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.$emit('successHandle')
            this.closeDialogHandle()
          })
        }
      })
    },
    // 关闭弹窗
    closeDialogHandle () {
      this.addData.isOpen = false
    }
  }
}
</script>
